package com.cn.jx.manager.service.query.Impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cn.jx.common.util.page.PageObj;
import com.cn.jx.manager.dao.RoleRepository;
import com.cn.jx.manager.dao.RoleResourceRepository;
import com.cn.jx.manager.dao.UserRoleRepository;
import com.cn.jx.manager.po.Resource;
import com.cn.jx.manager.po.Role;
import com.cn.jx.manager.po.RoleResource;
import com.cn.jx.manager.service.mtn.IResourceServiceMtn;
import com.cn.jx.manager.service.query.IResourceServiceQry;
import com.cn.jx.manager.service.query.IRoleServiceQry;
import com.jx.base.BaseService;
import com.jx.base.SessionUser;
import com.jx.jpaQuery.QueryCondition;
import com.jx.model.MenuEntry;
import com.jx.util.ArrayUtil;
import com.jx.util.Constant;
import com.jx.util.DateUtil;
import com.jx.util.MapObject;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since 
 * <p>创建时间：2019年12月1日
 * <p>功能描述：角色查询服务接口
 * <p>官方网站：management/admin/index
 * <p>邮箱地址：524577360@qq.com
 */
@Service("roleServiceQry") 
@Transactional
public class RoleServiceImplQry extends BaseService implements IRoleServiceQry {

	/**定义{@link RoleRepository roleDao <tt>角色Dao层接口定义</tt>}*/
	@Autowired
	private RoleRepository roleDao;
	
	/**定义{@link RoleResourceRepository roleResourceDao <tt>角色资源关系Dao层接口定义</tt>}*/
	@Autowired
	private RoleResourceRepository roleResourceDao;
	
	@Autowired
	private UserRoleRepository userRoleDao;
	
	@Autowired
	protected IResourceServiceMtn resourceServiceMtn;
	@Autowired
	protected IResourceServiceQry resourceServiceQry;
	

	/* 分页查询角色 */
	@Override
	@Transactional(readOnly = true)
	public PageObj<MapObject> findRoleByPageAndParams(QueryCondition cond) throws Exception {
		Specification<Role> speci = getSpecification(cond);
		Pageable pageable = getPageables(cond);
		Page<Role> res = roleDao.findAll(speci, pageable);
		List<Role> rescontent=res.getContent();
		List<MapObject> listContent=new ArrayList<MapObject>();
		if(ArrayUtil.listNotEmpty(rescontent)){
			rescontent.forEach(r->{
				MapObject mp=MapObject.getInstance();
				mp.put("roleName", r.getRoleName());
				mp.put("roleCode", r.getRoleCode());
				mp.put("descrb", r.getDescrb());
				mp.put("createTime", DateUtil.getDateFmt(r.getCreateTime()));
				mp.put("id", r.getId());
				listContent.add(mp);
			});
		}
		PageObj<MapObject> pageRes = PageObj.of(res, listContent);
		return pageRes;
	}
	
	/* 根据id获取角色 */
	@Override
	@Transactional(readOnly = true)
//	@RedisCacheSave(key = "roleServiceQry", value = "'getRoleById='.concat(#id)", rTime = RedisTime.SIX_HOURS, cls = Role.class)
	public Role getRoleById(String id) {
		return findEntityByPkid(id, Role.class);
	}

	/* 根据角色获取所有资源被选中的 */
	@Override
	@Transactional(readOnly = true)
//	@RedisCacheSave(key = "roleServiceQry", value = "'findAllResourceByRole='.concat(#roleId)", rTime = RedisTime.SIX_HOURS, cls = String.class)
	public Set<String> findAllResourceByRole(String roleId) {
		// 得到角色资源关系 有关系的
		List<RoleResource> rrlist = roleResourceDao.findRoleResourceByRoleId(roleId);
		Set<String> result = new HashSet<String>();
		if (rrlist != null && rrlist.size() > 0) {
			rrlist.forEach(rr->result.add(rr.getResourceId()));
		}
		// 返回资源ID集合
		return result;
	}

	/* 初始化sessionuser的资源角色 */
	@Override
	@Transactional(readOnly = true)
	public void initRoleResource(SessionUser suer) {
		String uid=suer.getUserId();
		//超级管理
		if(Constant._SUPER.equals(uid)){
			List<Resource> resource=resourceServiceQry.findAllResource();
			setSessionUserResource(suer,resource);
		}else{
			List<Role> listRole=roleDao.findRoleByUserId(uid);
			List<String> roleIds=new ArrayList<String>();
			if(listRole!=null && listRole.size()>0){
				suer.setRoleList(listRole);
				listRole.forEach(rl->roleIds.add(rl.getId()));
			}
			//资源编码设置到sessionuser中
			if(roleIds.size()>0){
				List<String>  resourceIds=roleResourceDao.findResourceIdByRoleIds(roleIds);
				//查询资源编码
				if(resourceIds!=null && resourceIds.size()>0){
					List<Resource>  resourceobj=resourceServiceQry.findAllResourceByIds(resourceIds);
					setSessionUserResource(suer,resourceobj);
				}
			}
		}
	}
	
	/**
	 * 
	* @Title:setSessionUserResource
	* @Description:TODO(给session里面设置resource)
	* <p>邮箱地址: 524577360@qq.com
	* @param suser
	* @param resourceobj
	* void
	* @throws
	 */
	private void setSessionUserResource(SessionUser suser,List<Resource>  resourceobj){
		if(resourceobj!=null && resourceobj.size()>0){
			suser.setResourceList(resourceobj);
			List<String> resourceCodes=new ArrayList<String>();
			resourceobj.forEach(rec->resourceCodes.add(rec.getCode()));
			suser.setResourceCodeList(resourceCodes);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public List<MenuEntry> findAllRole(String uid) {
		 List<String> selectedRoleIds=userRoleDao.findUserRoleByUserId(uid);
		 List<Role> allRole=roleDao.findAllRole();
		 List<MenuEntry> result=new ArrayList<MenuEntry>();
		 for(Role role:allRole) {
			 MenuEntry metr=new MenuEntry();
			 metr.setText(role.getRoleName());
			 metr.setCode(role.getRoleCode());
			 metr.setId(role.getId());
			 metr.setChecked(selectedRoleIds.contains(role.getId()));
			 result.add(metr);
		 }
		return result;
	}

	@Override
	@Transactional(readOnly = true)
	public String getRoleNamesByUserId(String userId) {
		List<String> rleName=roleDao.findRoleNamesByUserId(userId);
		if(rleName!=null && rleName.size()>0){
			StringBuffer result=new StringBuffer();
			rleName.forEach(L->result.append(L).append(Constant._COMMA));
			return result.deleteCharAt(result.length()-1).toString();
		}
		return Constant._EMPTY;
	}
}
